package com.yimi.yinhepda.views.exceptionsUpload_module;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.pda.ym.entity.response.NoDataResponse;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.callbacks.OnClickCallBack;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CompanyTableDao;
import com.yimi.yinhepda.db.table.CompanyTable;
import com.yimi.yinhepda.entity.bean.DictValueEntity;
import com.yimi.yinhepda.entity.request.Nohead;
import com.pda.ym.entity.bean.ImageInfo;
import com.pda.ym.entity.bean.ImageInfoResponse;
import com.yimi.yinhepda.entity.response.QueryGoodsLossResponse;
import com.yimi.yinhepda.entity.response.QueryJiTuoWuResponse;
import com.yimi.yinhepda.entity.response.QueryNoTitleTypeResponse;
import com.yimi.yinhepda.entity.response.QueryPackTypeResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.BitmapUtils;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.GlideImageLoader;
import com.pda.uce.commom.util.LogUtil;
import com.yimi.yinhepda.utils.PermissionUtils;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.utils.TransInformation;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 无头件上报界面
 *
 * @author 000432
 */
public class WithoutTitleBillActivity extends BaseActivity implements TextWatcher {
    /**
     * 件数、重量、体积、上一站、备注、发现库区、配载单号
     */
    private EditText piece, weight, volumn, preStation, remark, without_head_find_reservoir_area, without_head_car_code;
    /**
     * 已拍照片数
     */
    private TextView token_num;
    private Drawable defaulDraw;
    private Button backLayout;
    private Button saveLayout;
    private ArrayList<String> pickUrls;
    private CompanyTableDao mCompanyTableDao = new CompanyTableDao();
    /**
     * 上一环节部门
     */
    private String mDeptCode = "", mDeptName = "";
    /**
     * 上一环节所属企业编码
     */
    private String belongCompCode;
    private String image = "";
    /**
     * 选择对话框：无头件类型、寄托物、是否泄露、包装类型、发现环节(1-卸车，2-库存盘点)、经营属性（1、企业内，2、企业外）
     */
    private CustomSelectDialog csdNoTitleType, csdNoTitleAttr, csdJiTuoWu, csdGoodsLoss, csdPackType, csdFindLink, csdBussinessType;
    /**
     * 上传字段：无头件类型、无头件属性、寄托物、是否泄露货、包装类型、发现环节(1-卸车，2-库存盘点)、经营属性（1、企业内，2、企业外）
     */
    private Integer mProdType, mNoTitleAttr, mMailCarrier, mGoodsLoss, mPackType, mFindLink, mBussinessType;
    /**
     * 无头件类型数据字典key
     */
    private final String PROD_TYPE_KEY = "qc_nohead_production_type";
    /**
     * 无头件属性
     */
    private final String NO_TITLE_ATTR = "no_title_attr";
    /**
     * 寄托物数据字典key
     */
    private final String JI_TUO_WU_KEY = "jituowu_type";
    /**
     * 是否泄露货数据字典key
     */
    private final String GOODS_LOSS_KEY = "qc_nohead_weather_leakiness";
    /**
     * 包装类型数据字典key
     */
    private final String PACK_TYPE_KEY = "bz_type";
    /**
     * 发现库区
     */
    private final String FIND_LINK_KEY = "find_link_key";
    /**
     * 经营属性
     */
    private final String BUSSINESS_TYPE_KEY = "bussiness_type_key";
    /**
     * 图片选择器
     */
    private GalleryConfig galleryConfig;
    private final int PICURE_NUM = 15;
    /**
     * 选择图片路径
     */
    private List<String> pickPic;
    boolean isGalleryConfigPick = false;
    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA};
    private final int REQUEST_CODE_PERMISSIONS = 101;
    private final int SELECT_DEPT_REQUEST_CODE = 0;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_without_title_bill);
        initView();
        initValue();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pickUrls != null && pickUrls.size() > 0) {
            for (String item : pickUrls) {
                File file = new File(item);
                if (file.exists()) {
                    file.delete();
                }
            }
        }
    }

    @Override
    public String getPageName() {
        return "无头件上传";
    }

    public void initView() {
        //无头件类型
        csdNoTitleType = findViewById(R.id.csd_noTitleType);
        csdNoTitleType.setOnClickListener(this);
        //无头件属性
        csdNoTitleAttr = findViewById(R.id.csd_noTitleAttr);
        csdNoTitleAttr.setOnClickListener(this);
        //寄托物
        csdJiTuoWu = findViewById(R.id.csd_jiTuoWu);
        csdJiTuoWu.setOnClickListener(this);
        //是否泄露货
        csdGoodsLoss = findViewById(R.id.csd_goodsLoss);
        csdGoodsLoss.setOnClickListener(this);
        //包装类型
        csdPackType = findViewById(R.id.csd_packType);
        csdPackType.setOnClickListener(this);
        //发现环节
        csdFindLink = findViewById(R.id.csd_findLink);
        csdFindLink.setOnClickListener(this);
        //经营属性
        csdBussinessType = findViewById(R.id.csd_bussiness_type);
        csdBussinessType.setOnClickListener(this);
        findViewById(R.id.take_photo).setOnClickListener(this);
        piece = findViewById(R.id.without_head_piece);
        piece.addTextChangedListener(this);
        weight = findViewById(R.id.without_head_weight);
        volumn = findViewById(R.id.without_head_volumn);
        preStation = findViewById(R.id.et_preStation);
        preStation.setOnClickListener(this);
        preStation.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    toCreateDeptSelectActivity();
                }
            }
        });
        preStation.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(mDeptName) && preStation.getText().toString().length() > 0) {
                    preStation.setText("");
                    mDeptCode = "";
                    mDeptName = "";
                    startActivityForResult(new Intent(WithoutTitleBillActivity.this, CreateDeptSelectActivity.class), 0);
                    return;
                }

                if (!TextUtils.isEmpty(preStation.getText().toString().trim()) && !preStation.getText().toString().trim().equals(mDeptName)) {
                    preStation.setText("");
                    mDeptCode = "";
                    mDeptName = "";
                    startActivityForResult(new Intent(WithoutTitleBillActivity.this, CreateDeptSelectActivity.class), 0);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        remark =  findViewById(R.id.without_head_remark);
        without_head_find_reservoir_area =  findViewById(R.id.without_head_find_reservoir_area);
        without_head_car_code =  findViewById(R.id.without_head_car_code);
        //自动转成大写
        without_head_car_code.setTransformationMethod(new TransInformation());
        token_num =  findViewById(R.id.token_num);

        backLayout =  findViewById(R.id.img_back_layout);
        saveLayout =  findViewById(R.id.img_save_layout);
        backLayout.setOnClickListener(this);
        saveLayout.setOnClickListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void initValue() {
        defaulDraw = without_head_find_reservoir_area.getBackground();
        //图片保存路径
        pickUrls = new ArrayList<>();

        //初始化发现环节
        DictValueEntity valueEntity = new DictValueEntity("1", "卸车", true);
        csdFindLink.setDictValueEntity(valueEntity);
        csdFindLink.getTvSelectName().setText(valueEntity.getValue());
        mFindLink = Integer.parseInt(valueEntity.getKey());
        setEditStatus(mFindLink);

        //初始化经营属性
        DictValueEntity bussinessTypeEntity = new DictValueEntity("1", "企业内", true);
        csdBussinessType.setDictValueEntity(bussinessTypeEntity);
        csdBussinessType.getTvSelectName().setText(bussinessTypeEntity.getValue());
        mBussinessType = Integer.parseInt(bussinessTypeEntity.getKey());

        pickPic = new ArrayList<>();
        //初始化图片选择框架
        galleryConfig = new GalleryConfig.Builder()
                // 监听接口（必填）
                .iHandlerCallBack(iHandlerCallBack)
                // provider (必填)
                .imageLoader(new GlideImageLoader()).provider("com.yimi.yinhepda.fileprovider")
                // 记录已选的图片
                .pathList(pickPic)
                // 配置是否多选的同时 配置多选数量   默认：false
                .multiSelect(true, PICURE_NUM)
                // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false)
                // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .crop(false, 1, 1, 500, 500)
                // 是否实现相机按钮  默认：false
                .isShowCamera(true)
                // 图片存放路径
                .filePath("/Gallery/Pictures").build();
    }

    @Override
    public void onClick(View v) {
        List<DictValueEntity> dataList;
        switch (v.getId()) {
            case R.id.take_photo:
                //选择图片
                checkPersmisson();
                break;
            case R.id.csd_noTitleType:
                //无头件类型
                selectItemDialog("无头件类型", csdNoTitleType, QueryNoTitleTypeResponse.class, PROD_TYPE_KEY);
                break;
            case R.id.csd_noTitleAttr:
                //无头件属性
                dataList = new ArrayList<>();
                dataList.add(new DictValueEntity("1", "整件"));
                dataList.add(new DictValueEntity("2", "散件"));
                selectItemDialog2("无头件属性", csdNoTitleAttr, dataList, NO_TITLE_ATTR);
                break;
            case R.id.csd_jiTuoWu:
                //寄托物
                selectItemDialog("寄托物", csdJiTuoWu, QueryJiTuoWuResponse.class, JI_TUO_WU_KEY);
                break;
            case R.id.csd_goodsLoss:
                //是否泄露货
                selectItemDialog("是否泄露货", csdGoodsLoss, QueryGoodsLossResponse.class, GOODS_LOSS_KEY);
                break;
            case R.id.csd_packType:
                //包装类型
                selectItemDialog("包装类型", csdPackType, QueryPackTypeResponse.class, PACK_TYPE_KEY);
                break;
            case R.id.csd_findLink:
                //发现环节
                dataList = new ArrayList<>();
                dataList.add(new DictValueEntity("1", "卸车"));
                dataList.add(new DictValueEntity("2", "库存盘点"));
                selectItemDialog2("发现环节", csdFindLink, dataList, FIND_LINK_KEY);
                break;
            case R.id.csd_bussiness_type:
                //经营属性
                dataList = new ArrayList<>();
                dataList.add(new DictValueEntity("1", "企业内"));
                dataList.add(new DictValueEntity("2", "企业外"));
                selectItemDialog2("经营属性", csdBussinessType, dataList, BUSSINESS_TYPE_KEY);
                break;
            case R.id.img_back_layout:
                finish();
                break;
            case R.id.img_save_layout:
                //保存按钮
                save();
                break;
            case R.id.et_preStation:
                //上一环节
                toCreateDeptSelectActivity();
                break;
            default:
                break;
        }
    }

    /**
     * 图片加载框架，返回图接口
     */
    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            LogUtil.e("onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            LogUtil.e("onSuccess: 返回数据");
            for (String s : photoList) {
                LogUtil.e(s);
            }
            resetPicture(photoList);
        }

        @Override
        public void onCancel() {
            LogUtil.e("onCancel: 取消");
        }

        @Override
        public void onFinish() {
            LogUtil.e("onFinish: 结束");
        }

        @Override
        public void onError() {
            LogUtil.e("onError: 出错");
        }
    };

    private void resetPicture(final List<String> photoList) {

        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                pickPic.clear();
                if (photoList != null && photoList.size() > 0) {
                    pickPic.addAll(photoList);
                    for (int i = 0; i < photoList.size(); i++) {
                        Bitmap mBitmap = BitmapUtils.decodeSampledBitmapFromFile(photoList.get(i), 800, 1100);
                        BitmapUtils.compressBmpToFile(mBitmap, photoList.get(i));
                    }
                }
                if (!isGalleryConfigPick) {
                    galleryConfig.getBuilder().pathList(pickPic);
                }
                isGalleryConfigPick = false;
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                if (photoList != null) {
                    token_num.setText(photoList.size() + "");
                } else {
                    token_num.setText("0");
                }
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 选择数据对话框
     */
    private void selectItemDialog(String title, CustomSelectDialog selectDialog, Class<?> object, final String dictKey) {
        showPgDlg("获取数据中...");
        selectDialog.setTitle(title).queryDictValue(object, dictKey, new OnClickCallBack() {
            @Override
            public void onError(String msg) {
                dismissPgDlg();
                showToast(msg);
                SoundVibratorManager.playSound(2);
            }

            @Override
            public void onSuccess(Object obj) {
                dismissPgDlg();
            }

            @Override
            public void onCancle() {
            }

            @Override
            public void onSure(Object obj, Object dialog) {
                if (PROD_TYPE_KEY.equals(dictKey)) {
                    //无头件类型
                    mProdType = (Integer) obj;
                } else if (JI_TUO_WU_KEY.equals(dictKey)) {
                    //寄托物
                    mMailCarrier = (Integer) obj;
                } else if (GOODS_LOSS_KEY.equals(dictKey)) {
                    //是否泄露货
                    mGoodsLoss = (Integer) obj;
                } else if (PACK_TYPE_KEY.equals(dictKey)) {
                    //包装类型
                    mPackType = (Integer) obj;
                }
            }
        });
    }

    private void selectItemDialog2(String title, CustomSelectDialog selectDialog, List<DictValueEntity> dataList, final String key) {
        selectDialog.setTitle(title).setDialogDataList(dataList, new OnClickCallBack() {
            @Override
            public void onCancle() {

            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onSure(Object obj, Object obj1) {
                if (NO_TITLE_ATTR.equals(key)) {
                    //无头件属性
                    mNoTitleAttr = (Integer) obj;
                } else if (FIND_LINK_KEY.equals(key)) {
                    //发现环节
                    mFindLink = (Integer) obj;
                    if (mFindLink != null) {
                        setEditStatus(mFindLink);
                    }
                } else if (BUSSINESS_TYPE_KEY.equals(key)) {
                    //经营属性
                    mBussinessType = (Integer) obj;
                }
            }
        });
    }

    private void save() {
        if (mProdType == null) {
            SoundVibratorManager.playSound(2);
            showToast("请选择无头件类型！");
            return;
        }

        if (mNoTitleAttr == null) {
            SoundVibratorManager.playSound(2);
            showToast("请选择无头件属性！");
            return;
        }

        if (mMailCarrier == null) {
            SoundVibratorManager.playSound(2);
            showToast("请选择寄托物！");
            return;
        }

        if (mGoodsLoss == null) {
            SoundVibratorManager.playSound(2);
            showToast("请选择是否泄露货！");
            return;
        }

        if (mPackType == null) {
            SoundVibratorManager.playSound(2);
            showToast("请填写包装类型！");
            return;
        }

        if (TextUtils.isEmpty(piece.getText().toString().trim())) {
            SoundVibratorManager.playSound(2);
            showToast("请填写件数！");
            return;
        }

        if (Integer.parseInt(piece.getText().toString().trim()) == 0) {
            SoundVibratorManager.playSound(2);
            showToast("件数不能为0！");
            return;
        }

        if (!Common.isPositiveInteger(piece.getText().toString().trim())) {
            SoundVibratorManager.playSound(2);
            showToast("填写件数有误！");
            return;
        }

        if (TextUtils.isEmpty(weight.getText().toString().trim())) {
            SoundVibratorManager.playSound(2);
            showToast("请填写重量！");
            return;
        }

        if (!Common.isWeight(weight.getText().toString().trim())) {
            SoundVibratorManager.playSound(2);
            showToast("填写重量有误！");
            return;
        }

        if (!(0 < Double.parseDouble(weight.getText().toString().trim()) && Double.parseDouble(weight.getText().toString().trim()) <= 999999.99)) {
            SoundVibratorManager.playSound(2);
            showToast("重量在0—999999.99kg之间！");
            return;
        }

        if (TextUtils.isEmpty(volumn.getText().toString().trim())) {
            SoundVibratorManager.playSound(2);
            showToast("请填写体积！");
            return;
        }

        if (!Common.isWeight(volumn.getText().toString().trim())) {
            SoundVibratorManager.playSound(2);
            showToast("填写体积有误！");
            return;
        }

        if (!(0 < Double.parseDouble(volumn.getText().toString().trim()) && Double.parseDouble(volumn.getText().toString().trim()) <= 100)) {
            SoundVibratorManager.playSound(2);
            showToast("体积在0—100m³之间！");
            return;
        }

        if (mFindLink == null) {
            SoundVibratorManager.playSound(2);
            showToast("请选择发现环节！");
            return;
        } else if (mFindLink == 1) {
            if (TextUtils.isEmpty(preStation.getText().toString().trim())) {
                SoundVibratorManager.playSound(2);
                showToast("请填写上一环节！");
                return;
            }
            if (TextUtils.isEmpty(without_head_car_code.getText().toString().trim())) {
                SoundVibratorManager.playSound(2);
                showToast("请填写配载单！");
                return;
            }
            if (!StringUtils.isStowageNo(without_head_car_code.getText().toString().trim())) {
                SoundVibratorManager.playSound(2);
                showToast("配载单号不规范！");
                return;
            }
        } else if (mFindLink == 2) {
            if (TextUtils.isEmpty(without_head_find_reservoir_area.getText().toString().trim())) {
                SoundVibratorManager.playSound(2);
                showToast("请填写发现库区！");
                return;
            }
        }

        if (pickPic == null || pickPic.isEmpty()) {
            SoundVibratorManager.playSound(2);
            showToast("至少需要一张上报图片！");
            return;
        }

        if (remark.getText().toString().trim().equals("")) {
            SoundVibratorManager.playSound(2);
            showToast("请输入问题详情！");
            return;
        }
        uploadImage();
    }

    private void uploadImage() {
        if (pickPic != null && pickPic.size() > 0) {
            showPgDlg("正在保存无头件图片数据...");

            Map param = new HashMap();
            param.put("uploaderStrategyId", "4");

            NetRequest request = new NetRequest();
            for (int i = 0; i < pickPic.size(); i++) {
                String item = pickPic.get(i);
                String fileName = item.substring(item.lastIndexOf("/") + 1);
                request.addFile("file" + i, fileName, new File(item));
            }
            request.setParams(param)
                    .setMethod(NetRequest.Method.POST)
                    .setUrl(Constants.URL_UPLOAD_IMAGE)
                    .setResponsClazz(ImageInfoResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            SoundVibratorManager.playSound(2);
                            if (msg != null) {
                                showToast("无头件图片数据保存失败:" + msg);
                            } else {
                                showToast("无头件图片数据保存失败!");
                            }
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            ImageInfoResponse response = (ImageInfoResponse) obj;
                            for (ImageInfo item : response.getData()) {
                                image += (item.getFileKey() + ",");
                            }
                            image = image.substring(0, image.length() - 1);
                            upload();
                        }
                    });
        } else {
            upload();
        }
    }

    private void upload() {
        Nohead mNohead = new Nohead();
        mNohead.setEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
        mNohead.setEmpName(sharedPreferUtil.getValue(Common.USER_NAME));
        mNohead.setDeptCode(sharedPreferUtil.getValue(Common.DEPT_CODE));
        mNohead.setDeptName(sharedPreferUtil.getValue(Common.DEPT_NAME));
        mNohead.setCompCode(sharedPreferUtil.getCompanyCode());
        mNohead.setCompName(sharedPreferUtil.getCompanyName());
        mNohead.setPackType(mPackType);
        //寄托物
        mNohead.setMailCarrier(mMailCarrier);
        //是否泄露货
        mNohead.setGoodsLoss(mGoodsLoss);
        mNohead.setNum(Integer.parseInt(piece.getText().toString().trim()));
        mNohead.setWeight(Double.parseDouble(weight.getText().toString().trim()));
        mNohead.setVolume(Double.parseDouble(volumn.getText().toString().trim()));
        //发现环节 1-卸车，2-库存盘点
        mNohead.setFindLink(mFindLink);
        //发现库区
        mNohead.setFindReservoirArea(without_head_find_reservoir_area.getText().toString().trim());
        //配载单号
        mNohead.setCarCode(without_head_car_code.getText().toString().trim());
        //上一环节部门
        mNohead.setParentDeptCode(mDeptCode);
        mNohead.setParentDeptName(mDeptName);
        //上一环节部门所属企业
        mNohead.setParentCompCode(belongCompCode);
        List<CompanyTable> companyTableList = mCompanyTableDao.findCompCode(belongCompCode);
        if (companyTableList != null && companyTableList.size() > 0) {
            //上一环节部门所属企业名称
            mNohead.setParentCompName(companyTableList.get(0).getShortName());
        }
//        else {
//            SoundVibratorManager.playSound(2);
//            showToast("没查询到上一环节部门所属企业名称！");
//            return;
//        }
        //无头件类型
        mNohead.setProdType(mProdType);
        //无头件属性
        mNohead.setNoheadType(mNoTitleAttr);
        //经营属性（1、企业内，2、企业外）
        mNohead.setBusinessType(mBussinessType);
        mNohead.setDetail(remark.getText().toString().trim());
        mNohead.setImage(image);
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在保存无头件数据...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_UPLOAD_WITHOUT_TITLE)
                .setRequestObject(mNohead)
                .setResponsClazz(NoDataResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        if (msg != null) {
                            showToast("无头件数据保存失败:" + msg);
                        } else {
                            showToast("无头件数据保存失败!");
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(1);
                        showToast("无头件数据保存成功!");
                        finish();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_DEPT_REQUEST_CODE:
                    mDeptCode = data.getStringExtra("deptCode");
                    mDeptName = data.getStringExtra("deptName");
                    belongCompCode = data.getStringExtra("belongCompCode");
                    preStation.setText(mDeptName);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 跳转至网点查询界面
     */
    private void toCreateDeptSelectActivity() {
        Intent intent = new Intent(WithoutTitleBillActivity.this, CreateDeptSelectActivity.class);
        intent.putExtra("operateType", 1);
        intent.putExtra("inputType", 3);
        startActivityForResult(intent, SELECT_DEPT_REQUEST_CODE);
    }

    /**
     * 根据发现环节选项设置输入框状态
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setEditStatus(int position) {
        if (position == 1) {
            //选择卸车项时，【发现库区】置灰，无法输入，【上一环节】和【配载单号】为必填
            without_head_find_reservoir_area.setEnabled(false);
            //不可输入并清空
            without_head_find_reservoir_area.setText("");
            without_head_find_reservoir_area.setBackgroundColor(getResources().getColor(R.color.login_backline_color));
            preStation.setEnabled(true);
            preStation.setBackground(defaulDraw);
            without_head_car_code.setEnabled(true);
            without_head_car_code.setBackground(defaulDraw);
        } else if (position == 2) {
            //选择库存盘点时，【发现库区】为必填，【上一环节】和【配载单号】置灰，无法输入
            without_head_find_reservoir_area.setEnabled(true);
            without_head_find_reservoir_area.setBackground(defaulDraw);
            preStation.setEnabled(false);
            preStation.setBackgroundColor(getResources().getColor(R.color.login_backline_color));
            without_head_car_code.setEnabled(false);
            //不可输入并清空
            without_head_car_code.setText("");
            without_head_car_code.setBackgroundColor(getResources().getColor(R.color.login_backline_color));
        }
    }

    private void checkPersmisson() {
        PermissionUtils.checkMorePermissions(this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                galleryConfig.getBuilder().isOpenCamera(false).build();
                galleryConfig.getBuilder().pathList(pickPic);
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(WithoutTitleBillActivity.this);
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                PermissionUtils.requestMorePermissions(WithoutTitleBillActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(WithoutTitleBillActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(WithoutTitleBillActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        galleryConfig.getBuilder().isOpenCamera(false).build();
                        galleryConfig.getBuilder().pathList(pickPic);
                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(WithoutTitleBillActivity.this);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        PermissionUtils.requestMorePermissions(WithoutTitleBillActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Common.showPermissionDialog(WithoutTitleBillActivity.this, "程序需要读取手机信息权限和文件读写权限，才能继续使用，请去权限界面打开！", REQUEST_CODE_PERMISSIONS);
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().startsWith("0")) {
            //无头件件数不能输入0
            piece.setText("");
        }
    }
}
